#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/stat.h>
/*
I am a daemon
pid = 31739, pgid = 31738, sid=29013
after pid = 31739, pgid = 31739, sid=31739
 *
 */

int main(){
	pid_t pid;
	pid = fork();
	if(pid < 0){
		perror("fork");
		return 0;
	}else if(pid > 0){
		exit(0);
	}

	printf("I am a daemon\n");
	printf("pid = %d, pgid = %d, sid=%d\n", getpid(), getpgid(getpid()), getsid(getpid()));

	if(setsid() < 0){
		perror("setsid");
		exit(0);
	}

	printf("after pid = %d, pgid = %d, sid=%d\n", getpid(), getpgid(getpid()), getsid(getpid()));
	
	chdir("/");

	if(umask(0) < 0){
		perror("umask");
		exit(0);
	}

	close(0);
	close(1);
	close(1);

	sleep(100);
}
